package com.ruoyi.workflow.listener;

import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl;
import org.camunda.bpm.engine.impl.task.TaskDefinition;
import org.camunda.bpm.engine.impl.util.xml.Element;
import org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration;

/**
 * 配置全局监听器
 *
 * @author TD
 * @version 1.0
 * @date 2024/1/9
 */
public class GlobalBpmnParseListener extends AbstractBpmnParseListener {


    private static final StartMultiInstanceLoopCharacteristicsExecutionListener MULTI_LISTENER =
            new StartMultiInstanceLoopCharacteristicsExecutionListener();

    private static final InspectAssigneeTaskListener INSPECT_ASSIGNEE_LISTENER =
            new InspectAssigneeTaskListener();

    private static final StartProcessExecutionListener START_PROCESS_EXECUTION_LISTENER =
            new StartProcessExecutionListener();

    private static final EndProcessExecutionListener END_PROCESS_EXECUTION_LISTENER =
            new EndProcessExecutionListener();

    /**
     * 开始事件
     */
    @Override
    public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl startEventActivity) {
        startEventActivity.addListener(ExecutionListener.EVENTNAME_END, START_PROCESS_EXECUTION_LISTENER);
    }

    /**
     * 结束事件
     */
    @Override
    public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl endEventActivity) {
        endEventActivity.addListener(ExecutionListener.EVENTNAME_END, END_PROCESS_EXECUTION_LISTENER);
    }


    /**
     * 用户任务
     */
    @Override
    public void parseUserTask(Element userTaskElement, ScopeImpl scope, ActivityImpl activity) {
        UserTaskActivityBehavior behavior = (UserTaskActivityBehavior) activity.getActivityBehavior();
        TaskDefinition taskDefinition = behavior.getTaskDefinition();
        taskDefinition.addTaskListener(TaskListener.EVENTNAME_CREATE, INSPECT_ASSIGNEE_LISTENER);
    }

    /**
     * 多实例
     */
    @Override
    public void parseMultiInstanceLoopCharacteristics(Element activityElement, Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) {
        activity.addListener(ExecutionListener.EVENTNAME_START, MULTI_LISTENER);
    }
}
